/**
 * Created by udi on 17-4-11.
 */


var table_markdown = function (groupTables, withGroup,  dbName, groupMap,level) {
    const style = function (column, columnName) {
        var value = ((column[columnName] || "") + "").trim();
        if (column.isPrimary) {
            if (value) {
                return "**" + value + "**";
            }
            return "";
        }

        if (column.isVirtual && columnName.IsIn("name", "extra")) {
            if (value) {
                return "**" + value + "**";
            }
            return "";
        }

        if (column.name.IsIn("create_at", "update_at", "create_by", "update_by", "is_deleted")) {
            if (value) {
                return "*" + value + "*";
            }
            return "";
        }

        return value;
    }
    const gen_row = function (column) {
        if (column.isPrimary) {
            column.extra = "主键"
        } else if (column.isVirtual) {
            column.extra = "计算列"
        }

        return `| ${style(column, "columnIndex")} | ${style(column, "name")} | ${style(column, "sqlType")} | ${style(column, "remark")} | ${style(column, "extra")} |`
    }
    const gen_table = function (table) {
        var index = 1;
        table.columns.forEach(it => {
            it.columnIndex = (index++);
        });

        var ret = `
${'#'.repeat(level)}# \`${table.name}\` : ${table.comment}
|   序号  |   列名  |  类型  |  备注  |  特性  |
| ------ |------- | ------ | ------ | ------ |
` + table.columns.map(it => gen_row(it)).join("\n")

        return ret;
    }


    var ret = {};
    var groups =  groupTables.map(it=> it.key);

    groups.forEach(group => {
        var groupName  =  group
        if( groupMap[groupName] ) {
            groupName = groupMap[group];
        }
        var txts = [""];
        txts.push("#".repeat(level) +  " " + groupName + " 组")

        var tables = groupTables.find(it=>it.key == group).data;

        txts.push(`|   序号  |   表名  |  备注  |
| ------ |------- | ------ |`)

        var index = 0;
        txts.addAll(tables.map(it => {
            return `| ${++index} |  ${it.name} | ${it.comment}  |`
        }));


        txts.addAll(tables.map(table => gen_table(table)));

        ret[groupName] =  txts.join("\n");
    })

    return ret;
}

export default table_markdown
